package com.ruoyi.ums.auth.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.api.model.ThirdAuthUser;
import com.ruoyi.ums.auth.AuthRequestFactory;
import com.ruoyi.ums.auth.service.UmsLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 第三方登录
 */
@Slf4j
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UeitAuthController {

    private final AuthRequestFactory factory;
    @Autowired
    private UmsLoginService umsLoginService;
    @Autowired
    private TokenService tokenService;

    @GetMapping
    public List<String> list() {
        return factory.oauthList();
    }

    /**
     * 前端登录功能
     * 默认phone验证码登录。
     * 第三方登录，判断是否支持自动注册。支持：自动注册账号并登录  | 不支持：跳转至注册页面，缓存第三方授权信息，注册后自动登录绑定第三方
     * @param type
     * @param response
     * @throws IOException
     */



    @GetMapping("/login/{type}")
    public void login(@PathVariable String type, HttpServletResponse response) throws IOException {
        //当是手机号，邮箱，用户名登录时，跳转至umsLoginService的内部用户登录方法中
        AuthRequest authRequest = factory.get(type);
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }
    @PostMapping(value = "/{type}/callback")
    public R<?> login(@PathVariable String type, @RequestBody AuthCallback callback) {
        AuthRequest authRequest = factory.get(type);
        AuthResponse response = authRequest.login(callback);
        JSONObject a = JSONUtil.parseObj(JSONUtil.toJsonStr(response));
        AuthUser authUser = JSONUtil.toBean(a.getJSONObject("data"),AuthUser.class);
        //判断数据是否正确
        if(!a.get("code").equals(2000)){
            throw new BaseException("获取身份凭证出错，请重试");
        }
        //实现微信登录跳转
        switch (type){
            case "wechat_mp":
                ThirdAuthUser result = umsLoginService.WxRegAndLogin(authUser);
                LoginUser loginUser = new LoginUser();
                loginUser.setAccountId(result.getUmsAccountInfo().getAccountId());
                loginUser.setThirdAuthUser(result);
                return R.ok(tokenService.createToken(loginUser));
            default:
                break;
        }
        return R.ok();
    }
}
